﻿using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using FlyingHat.Common.Global;
using FlyingHat.Common.Helper;
using FlyingHat.Extensions.Aop;
using FlyingHat.Repository.IRepository;
using FlyingHat.Repository.Repository;

namespace FlyingHat.Extensions.ServiceExtensions
{
    public class AutofacModuleService
    {
        public static AutofacServiceProviderFactory RegisterAutofac()
        {
            var factory = new AutofacServiceProviderFactory(builder =>
            {
                builder.RegisterModule(new AutofacModule());
            });
            return factory;
        }
    }

    public class AutofacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {

            // AOP
            var cacheType = new List<Type>();
            builder.RegisterType<RedisCacheAop>();
            cacheType.Add(typeof(RedisCacheAop));

            // 依赖接口
            var baseType = typeof(IDependency);
            // 仓储注册
            var assemblyRepository = Assembly.Load("FlyingHat.Repository");
            builder.RegisterAssemblyTypes(assemblyRepository).Where(i => baseType.IsAssignableFrom(i) && i != baseType)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerLifetimeScope();

            // 服务注册
            var assemblyServices = Assembly.Load("FlyingHat.Service");
            builder.RegisterAssemblyTypes(assemblyServices)
            .Where(i => baseType.IsAssignableFrom(i) && i != baseType)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope()
             .EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
             .InterceptedBy(cacheType.ToArray())//允许将拦截器服务的列表分配给注册。
            ;

            // 单例注册
            // var single = typeof(ISingleInstance);
            // builder.RegisterAssemblyTypes(assemblyServices)
            //.Where(i => single.IsAssignableFrom(i) && i != single)
            //.AsImplementedInterfaces()
            //.SingleInstance();

        }
    }

}
